﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Management;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YJKFamilyLibDataManager
{
	public class FamilyUtil
	{
		public static bool IsWin32()
		{
			ConnectionOptions options = new ConnectionOptions();
			ManagementScope scope = new ManagementScope("\\\\localhost", options);
			ObjectQuery query = new ObjectQuery("select AddressWidth from Win32_Processor");
			ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(scope, query);
			ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
			string a = null;
			foreach (ManagementBaseObject managementBaseObject in managementObjectCollection)
			{
				ManagementObject managementObject = (ManagementObject)managementBaseObject;
				a = managementObject["AddressWidth"].ToString();
			}
			return a == "32";
		}

		public static void GetFamilyParams(UIApplication m_uiApp, string familyFileName, DataGridView dgv)
		{
			Document document = m_uiApp.Application.OpenDocumentFile(familyFileName);
			try
			{
				if (document.IsFamilyDocument)
				{
					FamilyManager familyManager = document.FamilyManager;
					FamilyParameterSet parameters = familyManager.Parameters;
					foreach (object obj in parameters)
					{
						FamilyParameter familyParameter = (FamilyParameter)obj;
						if (familyParameter.Formula == null)
						{
							string name = familyParameter.Definition.Name;
                            DisplayUnitType displayUnitType = (DisplayUnitType)(-2);
							try
							{
								displayUnitType = familyParameter.DisplayUnitType;
							}
							catch
							{
							}
							dgv.Rows.Add(new object[]
							{
								name,
								true,
								familyParameter.Definition.ParameterType,
								familyParameter.Id.IntegerValue,
								displayUnitType,
								familyParameter.StorageType,
								familyParameter.Definition.ParameterGroup
							});
						}
					}
				}
			}
			catch
			{
			}
			finally
			{
				document.Close(false);
			}
		}

		public static void GetFamilyTypeParams(UIApplication m_uiApp, string familyFileName, ListBox lbx, DbCategory category)
		{
			List<DbParamDefinition> paramDefinitionList = category.GetParamDefinitionList();
			lbx.Items.Clear();
			using (Document document = m_uiApp.Application.OpenDocumentFile(familyFileName))
			{
				try
				{
					if (document.IsFamilyDocument)
					{
						FamilyManager familyManager = document.FamilyManager;
						FamilyParameterSet parameters = familyManager.Parameters;
						int num = 0;
						foreach (object obj in parameters)
						{
							FamilyParameter familyParameter = (FamilyParameter)obj;
							if (familyParameter.Formula == null && !familyParameter.IsInstance)
							{
								string name = familyParameter.Definition.Name;
								DbParamDefinition dbParamDefinition = new DbParamDefinition(name, familyParameter.Definition.ParameterType, ParamDefinitionType.TypeParam, familyParameter.Definition.ParameterGroup);
								dbParamDefinition.StorageType = familyParameter.StorageType;
                                dbParamDefinition.DisplayUnitType = (DisplayUnitType)(-2);
								foreach (DbParamDefinition dbParamDefinition2 in paramDefinitionList)
								{
									if (dbParamDefinition2.Name == name)
									{
										dbParamDefinition.mLimit = true;
										break;
									}
								}
                                BuiltInParameterGroup builtInParameterGroup = (Autodesk.Revit.DB.BuiltInParameterGroup)(-1);
								try
								{
									builtInParameterGroup = familyParameter.Definition.ParameterGroup;
								}
								catch
								{
								}
								dbParamDefinition.BuiltInParameterGroup = builtInParameterGroup;
                                DisplayUnitType displayUnitType = (DisplayUnitType)(-2);
								try
								{
									displayUnitType = familyParameter.DisplayUnitType;
								}
								catch
								{
								}
								dbParamDefinition.DisplayUnitType = displayUnitType;
								ParameterType parameterType = 0;
								try
								{
									parameterType = familyParameter.Definition.ParameterType;
								}
								catch
								{
								}
								dbParamDefinition.ParameterType = parameterType;
								dbParamDefinition.CustomName = familyParameter.Definition.Name;
								dbParamDefinition.SetOrder(num);
								dbParamDefinition.StorageType = familyParameter.StorageType;
								num++;
								lbx.Items.Add(dbParamDefinition);
							}
						}
					}
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
				}
				finally
				{
					document.Close(false);
				}
			}
		}

		public static void GetFamilyInstanceParams(UIApplication m_uiApp, string familyFileName, ListBox lbx, ListBox lbxRecordParam)
		{
			lbx.Items.Clear();
			Family family = FamilyUtil.LoadFamily(m_uiApp.ActiveUIDocument.Document, familyFileName);
			if (family != null)
			{
				FamilySymbol familySymbol = null;
				using (List<FamilySymbol>.Enumerator enumerator = family.GetSymbols().GetEnumerator())
				{
					if (enumerator.MoveNext())
					{
						FamilySymbol familySymbol2 = enumerator.Current;
						familySymbol = familySymbol2;
					}
				}
				XYZ xyz = new XYZ();
                Autodesk.Revit.DB.View activeView = m_uiApp.ActiveUIDocument.Document.ActiveView;
				Transaction transaction = new Transaction(m_uiApp.ActiveUIDocument.Document, "temp");
				transaction.Start();
				UnifiedModified.ActivateFamilySymbol(familySymbol);
				FamilyInstance familyInstance = m_uiApp.ActiveUIDocument.Document.Create.NewFamilyInstance(xyz, familySymbol, 0);
				foreach (object obj in familyInstance.Parameters)
				{
					Parameter parameter = (Parameter)obj;
					DbParamDefinition dbParamDefinition = new DbParamDefinition(parameter.Definition.Name, parameter.Definition.ParameterType, ParamDefinitionType.InstanceParam, parameter.Definition.ParameterGroup);
                    dbParamDefinition.DisplayUnitType = DisplayUnitType.DUT_UNDEFINED;
					dbParamDefinition.StorageType = parameter.StorageType;
					try
					{
						dbParamDefinition.DisplayUnitType = parameter.DisplayUnitType;
					}
					catch
					{
					}
					foreach (object obj2 in lbxRecordParam.Items)
					{
						DbParamDefinition dbParamDefinition2 = obj2 as DbParamDefinition;
						if (dbParamDefinition2 != null)
						{
							//dbParamDefinition2.Name == dbParamDefinition.Name;
						}
					}
					lbx.Items.Add(dbParamDefinition);
				}
				m_uiApp.ActiveUIDocument.Document.Delete(familyInstance.Id);
				transaction.Commit();
				return;
			}
			MessageBox.Show("请检查族名是否符合规范。");
		}

		public static bool CanOpenDocument(UIApplication m_uiApp, string fileName)
		{
			bool result;
			try
			{
				m_uiApp.Application.OpenDocumentFile(fileName);
				result = true;
			}
			catch
			{
				result = false;
			}
			return result;
		}

		public static bool GetFamilyPreview(UIApplication m_uiApp, string familyFileName, PictureBox pbx)
		{
			bool result = false;
			try
			{
				Document document = m_uiApp.ActiveUIDocument.Document;
				Family family = FamilyUtil.LoadFamily(document, familyFileName);
				if (family != null)
				{
					pbx.Image = FamilyUtil.GetPreview(new Size(pbx.Size.Width, pbx.Size.Height), family);
					result = true;
				}
				else
				{
					result = false;
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
				result = false;
			}
			return result;
		}

		public static void ClearFamilyDataForAddFamily(UIApplication m_uiApp, string[] paths)
		{
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			DirectoryInfo directoryInfo = new DirectoryInfo(paths[0].Substring(0, paths[0].LastIndexOf("\\")));
			foreach (FileInfo fileInfo in directoryInfo.GetFiles())
			{
				if (fileInfo.Extension == ".rfa")
				{
					list.Add(fileInfo.FullName);
				}
			}
			Document document = m_uiApp.ActiveUIDocument.Document;
			string pathName = document.PathName;
			Document document2 = null;
			foreach (string text in paths)
			{
				bool flag = FamilyUtil.IsFileReadOnly(text);
				if (flag)
				{
					FamilyUtil.SetFileReadAccess(text, false);
				}
				UIDocument uidocument = m_uiApp.OpenAndActivateDocument(text);
				using (Transaction transaction = new Transaction(uidocument.Document, "Delete Schema Transaction"))
				{
					if (document2 != null)
					{
						document2.Close(true);
					}
					else
					{
						document.Close();
					}
					transaction.Start();
					Schema schema = Schema.Lookup(FamilyUtil.FamilyLibAddInGuid);
					if (schema != null)
					{
						Schema.EraseSchemaAndAllEntities(schema, false);
					}
					transaction.Commit();
					document2 = uidocument.Document;
				}
			}
			m_uiApp.OpenAndActivateDocument(pathName);
			if (document2 != null)
			{
				document2.Close(true);
			}
			foreach (FileInfo fileInfo2 in directoryInfo.GetFiles())
			{
				if (fileInfo2.Extension == ".rfa")
				{
					bool flag2 = true;
					foreach (string fullName in list)
					{
						if (FamilyUtil.GetName(fileInfo2.FullName) == FamilyUtil.GetName(fullName))
						{
							flag2 = false;
							break;
						}
					}
					if (flag2)
					{
						list2.Add(fileInfo2.FullName);
					}
				}
			}
			foreach (string path in list2)
			{
				File.Delete(path);
			}
		}

		public static void ClearFamilyData(UIApplication m_uiApp, string[] paths)
		{
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			DirectoryInfo directoryInfo = new DirectoryInfo(paths[0].Substring(0, paths[0].LastIndexOf("\\")));
			foreach (FileInfo fileInfo in directoryInfo.GetFiles())
			{
				if (fileInfo.Extension == ".rfa")
				{
					list.Add(fileInfo.FullName);
				}
			}
			Document document = m_uiApp.ActiveUIDocument.Document;
			string pathName = document.PathName;
			Document document2 = null;
			foreach (string text in list)
			{
				bool flag = FamilyUtil.IsFileReadOnly(text);
				if (flag)
				{
					FamilyUtil.SetFileReadAccess(text, false);
				}
				UIDocument uidocument = m_uiApp.OpenAndActivateDocument(text);
				using (Transaction transaction = new Transaction(uidocument.Document, "Delete Schema Transaction"))
				{
					if (document2 != null)
					{
						document2.Close(true);
					}
					else
					{
						document.Close();
					}
					transaction.Start();
					Schema schema = Schema.Lookup(FamilyUtil.FamilyLibAddInGuid);
					if (schema != null)
					{
						Schema.EraseSchemaAndAllEntities(schema, false);
					}
					transaction.Commit();
					document2 = uidocument.Document;
				}
			}
			m_uiApp.OpenAndActivateDocument(pathName);
			if (document2 != null)
			{
				document2.Close(true);
			}
			foreach (FileInfo fileInfo2 in directoryInfo.GetFiles())
			{
				if (fileInfo2.Extension == ".rfa")
				{
					bool flag2 = true;
					foreach (string fullName in list)
					{
						if (FamilyUtil.GetName(fileInfo2.FullName) == FamilyUtil.GetName(fullName))
						{
							flag2 = false;
							break;
						}
					}
					if (flag2)
					{
						list2.Add(fileInfo2.FullName);
					}
				}
			}
			foreach (string path in list2)
			{
				File.Delete(path);
			}
		}

		public static void SetFileReadAccess(string FileName, bool SetReadOnly)
		{
			FileInfo fileInfo = new FileInfo(FileName);
			fileInfo.IsReadOnly = SetReadOnly;
		}

		public static bool IsFileReadOnly(string FileName)
		{
			FileInfo fileInfo = new FileInfo(FileName);
			return fileInfo.IsReadOnly;
		}

		public static void ClearFamilyData(UIApplication m_uiApp)
		{
			List<string> list = new List<string>();
			List<string> list2 = new List<string>();
			FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
			if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
			{
				DirectoryInfo directoryInfo = new DirectoryInfo(folderBrowserDialog.SelectedPath);
				foreach (FileInfo fileInfo in directoryInfo.GetFiles())
				{
					if (fileInfo.Extension == ".rfa")
					{
						list.Add(fileInfo.FullName);
					}
					try
					{
						m_uiApp.Application.OpenDocumentFile(fileInfo.FullName);
					}
					catch
					{
						MessageBox.Show("文件夹中存在更高版本的Revit文件或包含非族文件。");
						return;
					}
				}
				Document document = m_uiApp.ActiveUIDocument.Document;
				string pathName = document.PathName;
				Document document2 = null;
				foreach (string text in list)
				{
					bool flag = FamilyUtil.IsFileReadOnly(text);
					if (flag)
					{
						FamilyUtil.SetFileReadAccess(text, false);
					}
					UIDocument uidocument = m_uiApp.OpenAndActivateDocument(text);
					using (Transaction transaction = new Transaction(uidocument.Document, "Delete Schema Transaction"))
					{
						if (document2 != null)
						{
							document2.Close(true);
						}
						else
						{
							document.Close();
						}
						transaction.Start();
						Schema schema = Schema.Lookup(FamilyUtil.FamilyLibAddInGuid);
						if (schema != null)
						{
							Schema.EraseSchemaAndAllEntities(schema, false);
						}
						transaction.Commit();
						document2 = uidocument.Document;
					}
				}
				m_uiApp.OpenAndActivateDocument(pathName);
				if (document2 != null)
				{
					document2.Close(true);
				}
				foreach (FileInfo fileInfo2 in directoryInfo.GetFiles())
				{
					if (fileInfo2.Extension == ".rfa")
					{
						bool flag2 = true;
						foreach (string fullName in list)
						{
							if (FamilyUtil.GetName(fileInfo2.FullName) == FamilyUtil.GetName(fullName))
							{
								flag2 = false;
								break;
							}
						}
						if (flag2)
						{
							list2.Add(fileInfo2.FullName);
						}
					}
				}
				foreach (string path in list2)
				{
					File.Delete(path);
				}
				MessageBox.Show("清理扩展数据成功。");
			}
		}

		public static void GetFamilyPreview1(UIApplication m_uiApp, string familyFileName, PictureBox pbx)
		{
			UIDocument uidocument = m_uiApp.OpenAndActivateDocument(familyFileName);
			Document document = uidocument.Document;
			string tempPath = Path.GetTempPath();
			FileInfo fileInfo = new FileInfo(tempPath + document.Title + ".jpg");
			try
			{
				ImageExportOptions imageExportOptions = new ImageExportOptions();
				imageExportOptions.FilePath = fileInfo.FullName;
				imageExportOptions.PixelSize = 600;
                imageExportOptions.ZoomType = (ZoomFitType)1;
                imageExportOptions.ShadowViewsFileType = (ImageFileType)1;
				List<ElementId> list = new List<ElementId>();
				FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document);
                ICollection<ElementId> collection = filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.View)).ToElementIds();
				foreach (ElementId item in collection)
				{
					list.Add(item);
				}
				imageExportOptions.SetViewsAndSheets(list);
				document.ExportImage(imageExportOptions);
				Image image = Image.FromFile(imageExportOptions.FilePath);
				if (image == null)
				{
					image = Resource1._null;
				}
				pbx.Image = image;
			}
			catch
			{
			}
		}

		public static Family LoadFamily(Autodesk.Revit.DB.Document doc, string familyFileName)
		{
			string name = FamilyUtil.GetName(familyFileName);
			Family family = ElementFiltering.FindFamily(doc, name);
			Transaction transaction = new Transaction(doc, "LoadFamily");
			try
			{
				if (family == null)
				{
					Family family2 = null;
					transaction.Start();
					doc.LoadFamily(familyFileName, out family2);
					transaction.Commit();
					family = family2;
				}
			}
			catch (Exception ex)
			{
				if ((int)transaction.GetStatus() == 1)
				{
					transaction.RollBack();
				}
				MessageBox.Show(ex.Message);
			}
			return family;
		}

		public static Family ReloadFamily(Autodesk.Revit.DB.Document doc, string familyFileName)
		{
			Family result = null;
			bool flag = false;
			Transaction transaction = new Transaction(doc, "LoadFamily");
			try
			{
				transaction.Start();
				flag = doc.LoadFamily(familyFileName, new FamilyUtil.MyFamilyLoadOptions(), out result);
				transaction.Commit();
			}
			catch
			{
				if ((int)transaction.GetStatus() == 1)
				{
					transaction.RollBack();
				}
			}
			if (!flag)
			{
				string name = FamilyUtil.GetName(familyFileName);
				result = ElementFiltering.FindFamily(doc, name);
			}
			return result;
		}

		public static FamilySymbol FindSymbol(Family family, string symbolName)
		{
			FamilySymbol result = null;
			List<FamilySymbol> symbols = family.GetSymbols();
			foreach (FamilySymbol familySymbol in symbols)
			{
				if (familySymbol.Name == symbolName)
				{
					result = familySymbol;
					break;
				}
			}
			return result;
		}

		public static string GetName(string fullName)
		{
			return Path.GetFileNameWithoutExtension(fullName);
		}

		public static Bitmap GetPreview(Size size, Family f)
		{
			Bitmap bitmap = Resource1._null;
			List<FamilySymbol> symbols = f.GetSymbols();
			if (symbols.Count <= 0)
			{
				return bitmap;
			}
			FamilySymbol familySymbol = null;
			using (List<FamilySymbol>.Enumerator enumerator = symbols.GetEnumerator())
			{
				if (enumerator.MoveNext())
				{
					FamilySymbol familySymbol2 = enumerator.Current;
					familySymbol = familySymbol2;
				}
			}
			try
			{
				bitmap = familySymbol.GetPreviewImage(size);
				bitmap.SetResolution(10f, 10f);
			}
			catch
			{
			}
			if (bitmap == null)
			{
				bitmap = Resource1._null;
			}
			return bitmap;
		}

		public static void UpdateGUIDTool(UIApplication app)
		{
			Document document = app.ActiveUIDocument.Document;
			try
			{
				foreach (FamilyLibDatabase familyLibDatabase in new List<FamilyLibDatabase>
				{
					FamilyLibDatabase.GetSqliteDB(SubjectType.Architecture, Convert.ToInt32(app.Application.VersionNumber).ToString()),
					FamilyLibDatabase.GetSqliteDB(SubjectType.Electric, Convert.ToInt32(app.Application.VersionNumber).ToString()),
					FamilyLibDatabase.GetSqliteDB(SubjectType.HVAC, Convert.ToInt32(app.Application.VersionNumber).ToString()),
					FamilyLibDatabase.GetSqliteDB(SubjectType.Plumbing, Convert.ToInt32(app.Application.VersionNumber).ToString()),
					FamilyLibDatabase.GetSqliteDB(SubjectType.System, Convert.ToInt32(app.Application.VersionNumber).ToString())
				})
				{
					if (MessageBox.Show(string.Format("正在更新{0}是否跳过。", familyLibDatabase.Name), "", MessageBoxButtons.YesNo) == DialogResult.No)
					{
						FileInfo fileInfo = new FileInfo("c:\\UpdateLog.txt");
						if (fileInfo.Exists)
						{
							fileInfo.Delete();
						}
						foreach (DbFamily dbFamily in familyLibDatabase.FamilyTable.GetAll())
						{
							FileInfo fileInfo2 = null;
							try
							{
								using (StreamWriter streamWriter = File.AppendText("c:\\UpdateLog.txt"))
								{
									streamWriter.WriteLine(dbFamily.Name + "，开始更新");
									dbFamily.Load(document, ref fileInfo2);
									familyLibDatabase.FamilyFileTable.Replace(dbFamily, fileInfo2);
									streamWriter.WriteLine(dbFamily.Name + "，更新完成");
								}
							}
							catch (Exception ex)
							{
								MessageBox.Show(ex.Message);
							}
							finally
							{
								if (fileInfo2.Exists)
								{
									fileInfo2.Delete();
								}
							}
						}
					}
				}
			}
			catch (Exception ex2)
			{
				MessageBox.Show(ex2.Message);
			}
		}

		public static void UpdateImgTool(UIApplication app)
		{
			Document document = app.ActiveUIDocument.Document;
			try
			{
				foreach (FamilyLibDatabase familyLibDatabase in new List<FamilyLibDatabase>
				{
					FamilyLibDatabase.GetSqliteDB(SubjectType.Architecture, Convert.ToInt32(app.Application.VersionNumber).ToString()),
					FamilyLibDatabase.GetSqliteDB(SubjectType.Electric, Convert.ToInt32(app.Application.VersionNumber).ToString()),
					FamilyLibDatabase.GetSqliteDB(SubjectType.HVAC, Convert.ToInt32(app.Application.VersionNumber).ToString()),
					FamilyLibDatabase.GetSqliteDB(SubjectType.Plumbing, Convert.ToInt32(app.Application.VersionNumber).ToString()),
					FamilyLibDatabase.GetSqliteDB(SubjectType.System, Convert.ToInt32(app.Application.VersionNumber).ToString())
				})
				{
					if (MessageBox.Show(string.Format("正在更新{0}是否跳过。", familyLibDatabase.Name), "", MessageBoxButtons.YesNo) == DialogResult.No)
					{
						foreach (DbFamily dbFamily in familyLibDatabase.FamilyTable.GetAll())
						{
							FileInfo fileInfo = null;
							try
							{
								using (StreamWriter streamWriter = File.AppendText("c:\\log.txt"))
								{
									streamWriter.WriteLine(dbFamily.Name);
								}
								fileInfo = familyLibDatabase.FamilyFileTable[dbFamily];
								Image largeImage = FamilyUtil.GetLargeImage(app.Application, fileInfo.FullName);
								familyLibDatabase.FamilyImgTable.UpdateLargeImg(dbFamily, largeImage);
							}
							catch
							{
							}
							finally
							{
								try
								{
									if (fileInfo.Exists)
									{
										fileInfo.Delete();
									}
								}
								catch
								{
								}
							}
						}
					}
				}
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

        public static Image GetLargeImage(Autodesk.Revit.ApplicationServices.Application app, string docFillPath)
		{
			Image result = Resource1._null;
			FamilyUtil.m_Option = new ImageExportOptions();
            FamilyUtil.m_Option.FitDirection = FitDirectionType.Horizontal;
            FamilyUtil.m_Option.HLRandWFViewsFileType = ImageFileType.JPEGLossless;
            FamilyUtil.m_Option.ImageResolution = ImageResolution.DPI_600;
            FamilyUtil.m_Option.ShouldCreateWebSite = false;
            FamilyUtil.m_Option.ExportRange = ExportRange.SetOfViews;
            FamilyUtil.m_Option.ZoomType = 0;
			FamilyUtil.m_Option.ViewName = "preview";

			Document document = app.OpenDocumentFile(docFillPath);
			ElementId elementId = null;
			string text = "";
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(document);
            FilteredElementIterator elementIterator = filteredElementCollector.OfClass(typeof(Autodesk.Revit.DB.View)).GetElementIterator();
			elementIterator.Reset();
			while (elementIterator.MoveNext())
			{
				Element element = elementIterator.Current;
                Autodesk.Revit.DB.View view = element as Autodesk.Revit.DB.View;
                if (view != null && !view.IsTemplate && (int)view.ViewType == 4 && (view.Name.CompareTo("{3D}") == 0 || view.Name.CompareTo("{三维}") == 0))
				{
					View3D view3D = view as View3D;
					XYZ xyz = new XYZ(-1.0, 1.0, -1.0);
					XYZ xyz2 = xyz * 10.0;
					XYZ xyz3 = xyz;
					XYZ xyz4 = new XYZ(xyz.X, xyz.Y, 0.0);
					xyz4 = DbGeometry.RotateTo(xyz4, -Math.PI*.5, XYZ.BasisZ);
					XYZ xyz5 = DbGeometry.RotateTo(xyz3, Math.PI*.5, xyz4);
					ViewOrientation3D orientation = new ViewOrientation3D(xyz2, xyz5, xyz3);
					view3D.SetOrientation(orientation);
					Transaction transaction = new Transaction(document);
					transaction.Start("set display style");
                    view3D.DisplayStyle = (DisplayStyle)8;
					view3D.get_Parameter(BuiltInParameter.VIEW_DETAIL_LEVEL).Set(FamilyUtil.m_DetailLevel);
					transaction.Commit();
					elementId = view3D.Id;
					text = view3D.Name;
					break;
				}
			}
			if (null == elementId)
			{
				Transaction transaction2 = new Transaction(document);
				try
				{
					transaction2.Start("shows ectionBox in the 3dView");
					XYZ direction = new XYZ(-1.0, 1.0, -1.0);
					View3D view3D2 = RevitVersionFuncs.NewView3D(document, direction);
                    view3D2.DisplayStyle = (DisplayStyle)8;
					view3D2.get_Parameter(BuiltInParameter.VIEW_DETAIL_LEVEL).Set(FamilyUtil.m_DetailLevel);
					text = view3D2.Name;
					transaction2.Commit();
					if (view3D2 == null)
					{
						document.Close(false);
						return result;
					}
					elementId = view3D2.Id;
				}
				catch
				{
					transaction2.RollBack();
					document.Close(false);
					return result;
				}
			}
			List<ElementId> list = new List<ElementId>();
			list.Add(elementId);
			string tempPath = Path.GetTempPath();
			string text2 = "temp";
			string filePath = tempPath + text2 + ".jpg";
			FamilyUtil.m_Option.FilePath = filePath;
			FamilyUtil.m_Option.SetViewsAndSheets(list);
			try
			{
				document.ExportImage(FamilyUtil.m_Option);
			}
			catch (Exception)
			{
				document.Close(false);
				return result;
			}
			string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(document.PathName);
			document.Close(false);
			string text3 = "三维视图";
			string text4 = string.Concat(new string[]
			{
				tempPath,
				text2,
				" - ",
				text3,
				" - ",
				text,
				".jpg"
			});
			if (!File.Exists(text4))
			{
				text3 = "3D View";
				text4 = string.Concat(new string[]
				{
					tempPath,
					text2,
					" - ",
					text3,
					" - ",
					text,
					".jpg"
				});
			}
			string text5 = tempPath + fileNameWithoutExtension + ".JPG";
			FamilyUtil.ChangeJPGSize(text4, text5);
			Image image = Image.FromFile(text5);
			result = (image.Clone() as Image);
			image.Dispose();
			try
			{
				File.Delete(text4);
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
			return result;
		}

		public static void TestGUID(UIApplication app)
		{
			UIDocument activeUIDocument = app.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			document.GetElement(activeUIDocument.Selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element));
		}

		private static void ChangeJPGSize(string imagePath, string exportFileFillPath)
		{
			Image image = Image.FromFile(imagePath);
			int num = ((Bitmap)image).Width;
			int num2 = ((Bitmap)image).Height;
			Bitmap bitmap = new Bitmap((Bitmap)image, num, num2);
			int width = bitmap.Width;
			int height = bitmap.Height;
			if (num2 > num)
			{
				num = num2;
			}
			else if (num > num2)
			{
				num2 = num;
			}
			float horizontalResolution = bitmap.HorizontalResolution;
			float verticalResolution = bitmap.VerticalResolution;
			float xDpi = 200f;
			float yDpi = 200f;
			try
			{
				Bitmap bitmap2 = new Bitmap(num, num2);
				Graphics graphics = Graphics.FromImage(bitmap2);
                SolidBrush brush = new SolidBrush(System.Drawing.Color.White);
				graphics.FillRectangle(brush, 0, 0, num, num2);
				int x = (int)((double)(num - width) / 2.0);
				int y = (int)((double)(num2 - height) / 2.0);
				graphics.DrawImage(bitmap, x, y, width, height);
				bitmap2.SetResolution(xDpi, yDpi);
				bitmap2.Save(exportFileFillPath, ImageFormat.Jpeg);
				image.Dispose();
				bitmap2.Dispose();
				bitmap.Dispose();
			}
			catch
			{
				image.Dispose();
				bitmap.Dispose();
			}
		}

		public static Guid FamilyLibAddInGuid = new Guid("356cda5a-e6c5-4c2f-a9ef-b3222116b8c8");

		private static ImageExportOptions m_Option = null;

		private static int m_DetailLevel = 3;

		private class MyFamilyLoadOptions : IFamilyLoadOptions
		{
			public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues)
			{
				overwriteParameterValues = true;
				return true;
			}

			public bool OnSharedFamilyFound(Family sharedFamily, bool familyInUse, out FamilySource source, out bool overwriteParameterValues)
			{
				source = 0;
				overwriteParameterValues = true;
				return true;
			}
		}

		public class PathIni
		{
			private static string GetIniPath()
			{
				return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "Hongye");
			}

			public static string ReadPath(string verNO)
			{
				string inipath = Path.Combine(FamilyUtil.PathIni.GetIniPath(), "HYBIMDB", "HYRME.ini");
				string text = new FamilyUtil.INIClass(inipath).IniReadValue(null, "Location");
				if (text == "")
				{
					return "";
				}
				bool flag = false;
				string path = Path.Combine(text, "FamilyLib");
				if (!Directory.Exists(path))
				{
					return "";
				}
				DirectoryInfo directoryInfo = new DirectoryInfo(path);
				foreach (FileInfo fileInfo in directoryInfo.GetFiles())
				{
					if (fileInfo.Name.Contains("Architecture"))
					{
						flag = true;
						break;
					}
				}
				if (flag)
				{
					return Path.Combine(text, "FamilyLib");
				}
				return "";
			}
		}

		public class INIClass
		{
			[DllImport("kernel32")]
			private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

			[DllImport("kernel32")]
			private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

			public INIClass(string INIPath)
			{
				this.inipath = INIPath;
			}

			public void IniWriteValue(string Section, string Key, string Value)
			{
				FamilyUtil.INIClass.WritePrivateProfileString(Section, Key, Value, this.inipath);
			}

			public string IniReadValue(string Section, string Key)
			{
				List<string> list = this.ReadSections(this.inipath);
				foreach (string section in list)
				{
					StringBuilder stringBuilder = new StringBuilder(500);
					FamilyUtil.INIClass.GetPrivateProfileString(section, Key, "", stringBuilder, 500, this.inipath);
					if (stringBuilder.ToString().CompareTo("") != 0)
					{
						return stringBuilder.ToString();
					}
				}
				return "";
			}

			[DllImport("kernel32")]
			private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, byte[] lpReturnedString, uint nSize, string lpFileName);

			public List<string> ReadSections(string iniFilename)
			{
				List<string> list = new List<string>();
				byte[] array = new byte[65536];
				uint privateProfileString = FamilyUtil.INIClass.GetPrivateProfileString(null, null, null, array, (uint)array.Length, iniFilename);
				int num = 0;
				int num2 = 0;
				while ((long)num2 < (long)((ulong)privateProfileString))
				{
					if (array[num2] == 0)
					{
						list.Add(Encoding.Default.GetString(array, num, num2 - num));
						num = num2 + 1;
					}
					num2++;
				}
				return list;
			}

			public bool ExistINIFile()
			{
				return File.Exists(this.inipath);
			}

			public string inipath;
		}
	}
}
